package com.tea.service.impl;

import java.sql.Connection;
import java.sql.SQLException;
import com.tea.dao.OrderDao;
import com.tea.util.DBUtil;

import com.tea.dao.OrderItemDao;
import com.tea.entity.Order;
import com.tea.entity.OrderItem;
import com.tea.service.OrderService;
import com.tea.servlet.CartServlet;


import java.sql.Timestamp;
import java.util.List;

public class OrderServiceImpl implements OrderService {
    private final OrderDao orderDao = new OrderDao();
    private final OrderItemDao orderItemDao = new OrderItemDao();

    @Override
    public String createOrder(Order order, List<OrderItem> cart) throws Exception {
        Connection conn = null;
        try {
            conn = DBUtil.getConnection();
            conn.setAutoCommit(false); // 禁用自动提交
            
            order.setOrderDate(new Timestamp(System.currentTimeMillis()));
            order.setStatus(0); // 初始状态：待付款
            order.setOrderId(new Timestamp(System.currentTimeMillis()).getTime());

            // 使用同一个连接添加订单
            long dbOrderId = orderDao.addOrder(order, conn);

            // 添加订单项并设置订单ID关联
            for (OrderItem item : cart) {
                item.setOrderId(dbOrderId);
                orderItemDao.addOrderItem(item, conn);
            }

            conn.commit(); // 提交事务
            return String.valueOf(dbOrderId);
        } catch (Exception e) {
            if (conn != null) {
                try {
                    conn.rollback(); // 回滚事务
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            throw e;
        } finally {
            if (conn != null) {
                try {
                    conn.setAutoCommit(true); // 恢复自动提交
                    conn.close(); // 关闭连接
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public Order getOrderById(long orderId) throws Exception {
        return orderDao.getOrderById(orderId);
    }

    @Override
    public List<Order> getOrdersByUserId(long userId) throws Exception {
        return orderDao.getOrdersByUserId(userId);
    }

    @Override
    public int updateOrderStatus(long orderId, int status) throws Exception {
        // 可以添加订单状态变更的业务逻辑，如状态流转验证等
        return orderDao.updateOrderStatus(orderId, status);
    }
}